//
//  RecommendViewController.m
//  DaDaLiCai
//
//  Created by admin on 15/11/10.
//  Copyright © 2015年 Mikeshihua. All rights reserved.
//
#include "ProductCell.h"
#import "RecommendViewController.h"
#import "SearchViewController.h"
#import "ProductDetailViewController.h"
#import "ProductModel.h"

@interface RecommendViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
@property (nonatomic,strong)UITableView * mainTableView;
@property (nonatomic,strong)NSMutableArray     * dataSourceArray;

@property (nonatomic, assign)int idx;
@property (nonatomic,assign) int n;
@property (nonatomic,strong)UIView *noDataView;
@property (nonatomic,strong)UIView *noNet;
@end

@implementation RecommendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self createTheNavigationBar];
    [self createTheUi];
}
-(void)createTheNavigationBar
{
    TopView *topView = [[TopView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_HEIGHT, 64.0f)];
    [topView setTitile:@"大大理财"];
    [self.view addSubview:topView];
}
-(void)createTheSearchBar
{
    //设置底部界面可遮盖。
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 44.0f)];
    topView.backgroundColor = [UIColor hexStringToColor:@"#ebebeb"];
    
    //    添加搜索框
    UIView * backView = [[UIView alloc]initWithFrame:CGRectMake(10, 5, SCREEN_WIDTH - 20, 34)];
    backView.backgroundColor = [UIColor whiteColor];
    backView.layer.cornerRadius = 5;
    [topView addSubview:backView];
    
    UIImageView * glassImageView = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2.0 - 44, 8, 18, 18)];
    glassImageView.image = [UIImage imageNamed:@"icon_search"];
    [backView addSubview:glassImageView];
    
    UILabel * tipLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2.0 - 26, 0, 30, 34)];
    tipLabel.text = @"搜索";
    tipLabel.textColor = [UIColor hexStringToColor:@"#969494"];
    tipLabel.font = [UIFont systemFontOfSize:15];
    [backView addSubview:tipLabel];
    
    UITapGestureRecognizer * gesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(gotoTheSearchViewController)];
    [topView addGestureRecognizer:gesture];
    _mainTableView.tableHeaderView = topView;
}
-(void)createTheUi
{
    _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64-49) style:UITableViewStyleGrouped];
    _mainTableView.dataSource = self;
    _mainTableView.delegate = self;
    _mainTableView.backgroundColor = [UIColor hexStringToColor:@"#ebebeb"];
    _mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _mainTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    [_mainTableView registerClass:[ProductCell class] forCellReuseIdentifier:@"cell"];
    _mainTableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTheTableView)];
    [self.view addSubview:_mainTableView];
    [_mainTableView addSubview:self.noNet];
    [_mainTableView addSubview:self.noDataView];
    [self createTheSearchBar];
    [_mainTableView.header beginRefreshing];
}
#pragma mark-----------dataSource和delegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataSourceArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ProductCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (_dataSourceArray.count >0)
    {
        ProductModel * model = _dataSourceArray[indexPath.section];
        cell.productTitle.text = model.paname;
        cell.productNumberLabel.text = [NSString stringWithFormat:@"编码：%@",model.pcode];
        float revate = ([model.revrate intValue])/10.0;
        [cell.advanceView setTheTitle1:@"预期收益" andTitle2:[NSString stringWithFormat:@"%.2f%%",revate]];
        [cell.timeView setTheTitle1:@"产品期限" andTitle2:[NSString stringWithFormat:@"%@天",model.revperiod]];
        
        if ([[NSString stringWithFormat:@"%@",model.paymethod] isEqualToString:@"1"]) {
            [cell.accessView setTheTitle1:@"付息方式" andTitle2:@"一次性付息"];
        }else if
            ([[NSString stringWithFormat:@"%@",model.paymethod] isEqualToString:@"4"])
        {
            [cell.accessView setTheTitle1:@"付息方式" andTitle2:@"按季付息"];
        }else
        {
            [cell.accessView setTheTitle1:@"付息方式" andTitle2:@"按半年付息"];
        }
        
        [cell.statusView setTheTitle1:@"产品状态" andTitle2:@"在售"];
        

    }
       return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ProductModel *model = _dataSourceArray[indexPath.section];
    
    ProductDetailViewController *productDetailViewCon = [[ProductDetailViewController alloc]initWithModel:model];
    [self.navigationController pushViewController:productDetailViewCon animated:TRUE];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 84;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0.01;
    }
    return 4;

}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    if (section == _dataSourceArray.count - 1) {
        return 0;
    }
    return 4;

}
#pragma mark --------------表的刷新与加载更多
-(void)refreshTheTableView
{
    _idx = 0;
    _n = 0;
    
    [self getHttpData];
}
- (void)AddtoTheProjectTableView
{
    [self getHttpData];
}
- (void)getHttpData
{
    _noDataView.hidden = TRUE;
    _noNet.hidden = TRUE;
    
    if (!_dataSourceArray) {
        _dataSourceArray = [NSMutableArray array];
    }
    _n++;
    
    NSDictionary * dict = @{@"page.size":[NSNumber numberWithInt:10],@"page.pn":[NSNumber numberWithInt:_idx + 1]};
    
    [AppGlobalClass PostDataWithNSstring:GETPRODUCTLIST withDictionary:dict success:^(NSDictionary *dictionary){
        
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
            [self.mainTableView.header endRefreshing];
            [self.mainTableView.footer setState:MJRefreshStateIdle];
            [self.mainTableView.footer endRefreshing];
            
            if(_idx == 0)
            {
                [_dataSourceArray removeAllObjects];
            }
            
            NSArray *dataArray = [dictionary objectForKey:@"responseData"];
            NSDictionary *dataDict = [dataArray firstObject];
            
            if([[dataDict objectForKey:@"pages"] intValue] > _idx)
            {
                
                NSMutableArray *listArray = [[[dictionary objectForKey:@"responseData"]firstObject] objectForKey:@"rows"];
                
                for(int i = 0; i < listArray.count; i++)
                {
                    NSDictionary * modelDict = listArray[i];
                    ProductModel * model = [[ProductModel alloc]initWithDictionary:modelDict];
                    [_dataSourceArray addObject:model];
                }
                
                _idx++;
                
                [self.mainTableView reloadData];
                
                if(_dataSourceArray.count < 10)
                {
                    [self.mainTableView.footer endRefreshingWithNoMoreData];
                }
                else
                {
                    if (_n<2) {
                        
                        self.mainTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(AddtoTheProjectTableView)];
                        
                    }
                    
                }
            }
            else
            {
                if (self.dataSourceArray.count==0) {
                    
                    //                    无数据
                    self.noDataView.hidden = FALSE;
                    
                }
                
                [self.mainTableView.footer endRefreshingWithNoMoreData];
            }
            
            
        }else
        {
            //没有真确返回
            [self.dataSourceArray removeAllObjects];
            [_mainTableView reloadData];
            _noDataView.hidden = FALSE;
            
            [self.mainTableView.header endRefreshing];
            [self.mainTableView.footer setState:MJRefreshStateIdle];
            [self.mainTableView.footer endRefreshing];
        }
        
        
        
    } failure:^(NSError *error){
        [self.mainTableView.header endRefreshing];
        [self.mainTableView.footer setState:MJRefreshStateIdle];
        [self.mainTableView.footer endRefreshing];
        //     无数据
        _noDataView.hidden = FALSE;
        [_dataSourceArray removeAllObjects];
        [self.mainTableView reloadData];
    } networkerror:^(NSString *networkerror){
        [self.dataSourceArray removeAllObjects];
        [self.mainTableView.header endRefreshing];
        [self.mainTableView.footer setState:MJRefreshStateIdle];
        [self.mainTableView.footer endRefreshing];
        [self.mainTableView reloadData];
        _noNet.hidden = FALSE;
        [_dataSourceArray removeAllObjects];
        [self.mainTableView reloadData];
        //       无网络图标
    }];
}
//没网提示
#pragma mark - 无网提示
#pragma mark - 没网提示
-(UIView *)noNet
{
    if (!_noNet) {
        _noNet = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
        _noNet.center = CGPointMake(_mainTableView.center.x, _mainTableView.center.y - 64 - 32);
        _noNet.hidden = TRUE;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 200, 200);
        [button setImage:[UIImage imageNamed:@"img_nonetwork"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonAgainTapped:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 200 - 40, 200, 44)];
        label.text = @"网络不通\n点击重新搜索";
        label.textAlignment = NSTextAlignmentCenter;
        label.numberOfLines = 0;
        label.font = [UIFont systemFontOfSize:14.0f];
        
        label.textColor = [UIColor colorWithWhite:0.000 alpha:0.540];
        [_noNet addSubview:label];
        [_noNet addSubview:button];
    }
    return _noNet;
}

-(UIView *)noDataView{
    if (!_noDataView) {
        
        _noDataView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
        _noDataView.center =CGPointMake(_mainTableView.center.x, _mainTableView.center.y - 64 - 32);
        _noDataView.hidden = TRUE;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 200, 200);
        [button setImage:[UIImage imageNamed:@"img_nodata"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonAgainTapped:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 200 - 40, 200, 44)];
        label.text = @"暂无数据\n点击重新搜索";
        label.textAlignment = NSTextAlignmentCenter;
        label.numberOfLines = 0;
        label.font = [UIFont systemFontOfSize:14.0f];
        
        label.textColor = [UIColor colorWithWhite:0.000 alpha:0.540];
        [_noDataView addSubview:label];
        [_noDataView addSubview:button];
    }
    
    return _noDataView;
}
- (void)buttonAgainTapped:(id)sender
{
    [self.mainTableView.header beginRefreshing];
}


-(void)gotoTheSearchViewController
{
    SearchViewController *vc = [[SearchViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
